package com.darrenchan.leetcode;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-02-29 17:01
 */
public class ConnectingGraph3 {
    private int[] father = null;
    private int cnt;

    private int find(int x) {
        if(x == father[x]) {
            return x;
        }

        return father[x] = find(father[x]);
    }

    public ConnectingGraph3(int n) {
        // initialize your data structure here.
        father = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            father[i] = i;
        }

        cnt = n;
    }

    public void connect(int a, int b) {
        // write your code here
        int fatherA = find(a);
        int fatherB = find(b);

        if(fatherA != fatherB) {
            father[fatherA] = fatherB;
            cnt--;
        }
    }

    /**
     * @return: An integer
     */
    public int query() {
        // write your code here
        return cnt;
    }
}
